package com.ht.sps.module;

import com.ht.sps.nh.bui.model.SimulateSideEnumNode;
import com.ht.sps.nh.entity.TreeMenu;
import com.ht.sps.nh.entity.User;
import com.ht.sps.nh.service.NhUserService;
import com.ht.sps.nh.service.TreeMenuService;
import com.octo.captcha.service.CaptchaServiceException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.nutz.integration.shiro.realm.NutDaoRealm;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.*;
import org.nutz.web.ajax.Ajax;
import org.nutz.web.ajax.AjaxReturn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@IocBean
public class IndexModule {
    private static final Logger log = LoggerFactory.getLogger(IndexModule.class);

    @Inject
    private NhUserService nhUserService;

    @Inject
    private TreeMenuService treeMenuService;

    @At
    @Ok("th:main")
    @RequiresAuthentication
    public void admin(HttpServletRequest request) {
        Subject currentUser = SecurityUtils.getSubject();
        NutDaoRealm.ShiroUser user = (NutDaoRealm.ShiroUser) currentUser.getPrincipal();
        User loginUser = nhUserService.fetch(user.getId());
        if(loginUser.getType()==0){
            List<SimulateSideEnumNode> nodeList= getSideEnumNode(user.getId().longValue());
            request.setAttribute("nodeList",nodeList);
        }
        request.setAttribute("pic1",png(request,"3"));
        request.setAttribute("pic2",png(request,"4"));
        request.setAttribute("currentUser", user);
        request.setAttribute("shiro", currentUser);
        request.setAttribute("system",loginUser.getType()==1?true:false);

    }

    @At({"/", "/login"})
    @GET
    @Ok("th:login")
    public void login(HttpServletRequest request) {
        log.debug("用户登录");
        request.setAttribute("pic1",png(request,"1"));
        request.setAttribute("pic2",png(request,"2"));
    }

    @At
    @POST
    @Fail(">>:/")
    @Ok("fastjson")
    public AjaxReturn login(@Param("username") String username,
                            @Param("password") String password,
                            @Param("remeberMe") boolean remeberMe,
                            HttpServletRequest request) {
        log.debug("用户登录{}:{}", username, password);

        if (Strings.isBlank(username)) {
            return Ajax.fail().setMsg("请输入您的用户名!");
        } else if (Strings.isBlank(password)) {
            return Ajax.fail().setMsg("请输入您的密码!");
        } else {
            try {
                Subject currentUser = SecurityUtils.getSubject();
                UsernamePasswordToken token = new UsernamePasswordToken(username, password);
                token.setRememberMe(remeberMe);
                currentUser.login(token); // 这里的授权,请查看shiro.ini中的nutRealm
                return Ajax.ok();
            } catch (CaptchaServiceException e) {
                return Ajax
                        .fail()
                        .setMsg("Invalid ID, could not validate unexisting or already validated captcha");
            } catch (LockedAccountException e) {
                return Ajax.fail().setMsg("帐号已被锁定");
            } catch (AuthenticationException e) {
                e.printStackTrace();
                return Ajax.fail().setMsg("密码错误或用户不存在");
            } catch (Exception e) {
                e.printStackTrace();
                return Ajax.fail().setMsg("登录失败");
            }
        }
    }

    // 没登录就不要登出了
    @RequiresAuthentication
    @At
    @Ok(">>:/")
    public void logout() {
        SecurityUtils.getSubject().logout();
    }


    public String png(HttpServletRequest request,String photoName) {
        String path = null;
        if(photoName!=null&&!photoName.equals("")){
            String jpgPath = request.getServletContext().getRealPath("/resources/nh/images/"+photoName+".jpg");
            String pngPath = request.getServletContext().getRealPath("/resources/nh/images/"+photoName+".png");
            if (new File(jpgPath).exists()) {
                path = "/resources/nh/images/"+photoName+".jpg";
            } else if (new File(pngPath).exists()) {
                path = "/resources/nh/images/"+photoName+".png";
            }
        }

        if (path == null) {
            switch (Integer.parseInt(photoName)){
                case 1: path ="/resources/nh/images/login.png";break;
                case 2: path ="/resources/nh/images/input.jpg";break;
                case 3: path ="/resources/nh/images/main.png";break;
                case 4: path ="/resources/nh/images/title.png";break;
                default: path ="/resources/nh/images/login.png";break;
            }
        }

        return path;
    }

    public List<SimulateSideEnumNode> getSideEnumNode(Long userId){

        List<SimulateSideEnumNode> simlateSideEnumNodes = new ArrayList();
        //数据接口获得数据为已排序好的数据及pid,level,id

        List<TreeMenu> treeMenus = treeMenuService.getTreeMenuListByUserId(userId);
        for (TreeMenu tm:treeMenus){
            if (tm.getMenuLevel() == 1) {
                simlateSideEnumNodes.add(new SimulateSideEnumNode(tm));
            } else if (tm.getMenuLevel() == 2) {
                for (SimulateSideEnumNode sse : simlateSideEnumNodes) {
                    if (sse.getId() == tm.getParentId()){
                        sse.getItems().add(new SimulateSideEnumNode(tm));
                        break;
                    }
                }
            } else if (tm.getMenuLevel() == 3) {
                boolean isHave = false;
                for (SimulateSideEnumNode sse : simlateSideEnumNodes) {

                    for (SimulateSideEnumNode secondSse :sse.getItems()){
                        if (secondSse.getId() == tm.getParentId()){
                            secondSse.getItems().add(new SimulateSideEnumNode(tm));
                            isHave = true;
                            break;
                        }
                    }
                    if (isHave){
                        break;
                    }
                }
            }
        }


        return simlateSideEnumNodes;
    }
}
